package com.app.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

public class AliyunSmsSender {

    private static final String ACCESS_KEY_ID = "LTAI5tQFNKfmZn6mtZeBwNWF";
    private static final String ACCESS_KEY_SECRET = "LAmHX119PU77wts7KmHktvBJWu12Hy";
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";

    public static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        // 访问的域名
        config.endpoint = ENDPOINT;
        return new Client(config);
    }

    public static JSONObject sendSms(String phoneNumber, String templateCode, String templateParam) {
        try{
            System.err.println("短信参数----"+templateParam);
            System.err.println("收信手机号----"+phoneNumber);
            Client client = createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName("甘肃致卓新辉商贸")
                    .setTemplateCode(templateCode)
                    .setTemplateParam(templateParam);
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            JSONObject result = new JSONObject();
            result.put("Code", response.getBody().getCode());
            result.put("Message", response.getBody().getMessage());
            System.err.println("发送短信返回报文---"+result.toJSONString());
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            // 接收短信的手机号码
            String phoneNumber = "18219979760";
            // 短信签名名称

            // 短信模板CODE
            String templateCode = "SMS_479155052";
            // 短信模板变量对应的实际值，JSON格式
            JSONObject templateParam = new JSONObject();
            templateParam.put("name", "马杰");
            templateParam.put("project", "项目名称");
            templateParam.put("reason", "测试原因");
            templateParam.put("contact", "09374421329");


            JSONObject result = sendSms(phoneNumber, templateCode, templateParam.toJSONString());
            System.err.println(result.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}